/**
 * 帖子编辑页
 */

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  FlatList,
  TouchableHighlight,
  TouchableOpacity,
  Image,
  Dimensions,
  KeyboardAvoidingView,
  TextInput,
  ImageBackground,
  AsyncStorage,
} from 'react-native';

import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import Config from '../common/config';
import Request from '../common/request';
import Toast from 'react-native-root-toast';
import ImagePicker from 'react-native-image-picker';
import ImageZoom from 'react-native-image-pan-zoom';
import RNFetchBlob from 'react-native-fetch-blob';


let width = Dimensions.get('window').width;//获取视口宽度

let pickPhotoOptions = {
  title: '选择图片',
  cancelButtonTitle: "取消",
  chooseFromLibraryButtonTitle: "从相册选择",
  takePhotoButtonTitle: "拍照",
  allowsEditing: false,
  noData: false,
  storageOptions: {
    skipBackup: true,
    path: 'images'
  }
};

let getMimeTypeFromFilename = (filename) => {
  let pos = filename.lastIndexOf(".") + 1;
  let ext = filename.substr(pos).toLowerCase();
  if (ext == "jpg" || ext == "jpeg") {
    return "image/jpeg";
  } else {
    return "image/" + ext;
  }
}

class TopicEdit extends React.Component {
  static navigationOptions = ({navigation, screenProps}) => ({
    headerTitle: `编辑内容`,
    headerLeft: (
      <TouchableOpacity onPress={() => {navigation.goBack()}} style={{marginLeft: 10}}>
        <Icon name="close" size={24} />
      </TouchableOpacity>
    ),
    headerRight: (
      <TouchableOpacity onPress={() => {navigation.state.params.handleSubmit()}} style={{marginRight: 15}}>
        <Text style={{color: "green", fontSize: 18}}>提交</Text>
      </TouchableOpacity>
    )
  })
  constructor(props) {
    super(props);
    this.state = {
      fid: null,
      page: 1,//下一次请求的页码
      pagination: null,
      loading: false,
      refreshing: false,
      data: [],
      textInputTitle: "",
      textInputContent: "",
      attachmentIdArr: [],
      selectedImages: [
        // {uri: "http://www.xiaomlove.com/demo/images/girl.jpg"},
        // {uri: "http://www.xiaomlove.com/demo/images/lunbo/4.jpg"},
        // {uri: "http://www.xiaomlove.com/demo/images/lunbo/5.jpg"},
      ],
      uploadProgressValue: 0,
      uploadProgressText: "上传中...",
    };
  }
  componentDidMount() {
    this.props.navigation.setParams({
      handleSubmit: this.onSubmit.bind(this)
    });
    // this.setState({
    //   refreshing: true,
    //   fid: this.props.navigation.state.params.id
    // }, () => {
    //   this.fetchTopics();
    // })
    
  }

  hideKeyBoard() {
    this.refs["textInputTitle"].blur();
    this.refs["textInputContent"].blur();
  }

  updateProgress(progressValue, progressText, activeImage) {
    // let images = this.state.selectedImages;
    // images.map((item, i) => {
    //   if (item.fileName == activeImage.fileName && item.timestamp == activeImage.timestamp) {
    //     item.progressValue = progressValue;
    //     item.progressText = progressText;
    //     images[i] = item;
    //     return false;
    //   }
    // });
    //console.log("images:", images);
    this.setState({uploadProgressValue: progressValue, uploadProgressText: progressText});
  }

  pickPhoto() {
    if (this.state.loading) {
      Toast.show("上传中...");
      return;
    }
    var self = this;
    ImagePicker.showImagePicker(pickPhotoOptions, (response) => {
      console.log('Response = ', response);

      if (response.didCancel) {
        console.log('User cancelled image picker');
      }
      else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      }
      else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      }
      else {

        let source = { uri: response.uri };
        //response.url = response.uri;

        // You can also display the image using data:
        let image = 'data:image/jpeg;base64,' + response.data;

        this.setState({
          selectedImages: [...this.state.selectedImages, response],
          loading: true,
        }, async () => {
          //开始上传
          var token = await Request.getToken();
          console.log("upload token: ", token);
          RNFetchBlob.fetch('POST', Config.api.upload, {
            //... some headers,
            "Accept": "application/json",
            "Authorization": "Bearer " + token,
            "Content-Type" : "multipart/form-data" 
          }, [
            {
              name: "image[]", 
              filename: response.fileName, 
              type: getMimeTypeFromFilename(response.fileName), 
              data: RNFetchBlob.wrap(response.origURL)
            }
          ])
          // listen to upload progress event
          .uploadProgress((written, total) => {
            let progress = (written / total) * 100;
            progress = Math.floor(progress);
            console.log('uploaded: ', progress);
            self.updateProgress(progress, "上传中...", response);
          })
          // listen to download progress event
          .progress((received, total) => {
            console.log('downloaded: ', received / total);
          })
          .then((resp) => {
            var result = JSON.parse(resp.data);
            console.log("finished: ", result);
            self.updateProgress(100, "上传完成", response);
            self.setState({
              attachmentIdArr: [...this.state.attachmentIdArr, result.data[0].id],
              loading: false,
            });
          })
          .catch((err) => {
            console.log('err: ', err);
          })
          

        });
      }
    });
  }

  onSubmit() {
    var self = this;
    if (this.state.loading) {
      return;
    }
    let data = {
      title: this.state.textInputTitle,
      content: this.state.textInputContent,
      fid: this.props.navigation.state.params.fid,
      attachment_id: this.state.attachmentIdArr,
    }
    this.setState({
      loading: true,
    })
    if (!data.title || !data.content) {
      Toast.show("请先填写标题和内容...");
      return;
    }
    //Toast.show(JSON.stringify(data));
    Request.post(Config.api.topic, data)
    .then((response) => {
      console.log(response);
      self.setState({
          loading: false,
      })
      if (response.ret == 0) {
        Toast.show("发表成功：" + response.data.topic.id);
        self.props.navigation.goBack();
      } else {
        Toast.show(response.msg);
      }
    })
  }

  fetchTopics() {
    var self = this;
    Request.get(Config.api.topic, "fid=" + self.state.fid + "&page=" + self.state.page)
    .then((response) => {
      console.log(response);
      self.setState({
        refreshing: false,
        loading: false,
      });
      if (response.ret == 0) {
        if (response.data.pagination.current_page == 1) {
          var newData = response.data.list;
        } else {
          var newData = [...self.state.data, ...response.data.list];
        }
        self.setState({
          data: newData,
          pagination: response.data.pagination,
          page: response.data.pagination.current_page + 1,
        });
      } else {
        AlertIOS.alert(response.msg);
      }
      
    })
  }

  doPreview(index) {
    if (this.state.loading) {
      Toast.show("上传中...");
      return;
    }
    this.props.navigation.navigate("ImagePreview", {images: this.state.selectedImages, index: index});
  }


  render() {
    let self = this;
    let Images = this.state.selectedImages.map((item, i) => {
      return (
        <TouchableOpacity key={i} onPress={() => this.doPreview(i)}>
          <ImageBackground style={[styles.imageItem]} source={{uri: item.uri}}>
            <Text style={styles.uploadStatus}>{self.state.uploadProgressText}</Text>
            <Text style={styles.uploadStatus}>{self.state.uploadProgressValue}%</Text>
            <View style={[styles.mask, {height: (100 - self.state.uploadProgressValue) + "%"}]}></View>
          </ImageBackground>
        </TouchableOpacity>
      )
    })
    return (
      <TouchableOpacity style={styles.container} onPressIn={() => this.hideKeyBoard()} activeOpacity={1}>
        <KeyboardAvoidingView>
          <TextInput 
            ref={"textInputTitle"}
            style={[styles.textInputTitle, styles.textInput]}
            onChangeText={(text) => this.setState({textInputTitle: text})}
            placeholder={"标题"}
            multiline={false}
            underlineColorAndroid="transparent"
          />
          <TextInput 
            ref={"textInputContent"}
            style={[styles.textInputContent, styles.textInput]}
            onChangeText={(text) => this.setState({textInputContent: text})}
            placeholder={"内容"}
            multiline={true}
            underlineColorAndroid="transparent"
          />
          <View style={styles.imageBox}>
            {/* <Image style={[styles.imageItem, styles.image]} source={require('../asset/image/2.png')} /> */}
            {Images}
            <TouchableOpacity 
              style={[styles.imageItem, styles.btnAddImage]}
              activeOpacity={0.8}
              onPress={() => this.pickPhoto()}
            >
              <Icon  name="plus" size={50} />
            </TouchableOpacity>
          </View>
        </KeyboardAvoidingView>
      </TouchableOpacity>      
    );
  }
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
    height: "100%",
    padding: 15,
  },
  textInput: {
    fontSize: 16,
    padding: 10
  },
  textInputTitle: {
    borderBottomWidth: 1,
    borderBottomColor: "#ddd",
  },
  textInputContent: {
    paddingTop: 20,
    height: 150,
  },
  imageBox: {
    flexDirection: "row",
  },
  image: {
    resizeMode: "cover",
  },
  imageItem: {
    height: 50,
    width: 50,
    marginRight: 5,
    alignItems: "center",
    justifyContent: "center",
    position: "relative",
  },
  btnAddImage: {
    borderWidth: 0,
    borderColor: "#aaa",
    borderStyle: "dotted",
    alignItems: "center",
    justifyContent: "center",
  },
  uploadStatus: {
    fontSize: 10,
    color: "white",
    backgroundColor: "transparent",
    zIndex: 9999,
    position: "relative",
  },
  mask: {
    position: "absolute",
    left: 0,
    bottom: 0,
    width: "100%",
    height: "100%",
    backgroundColor: "rgba(0, 0, 0, 0.5)",
    zIndex: 999,
  }


});

module.exports = TopicEdit;

